﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using nanoCMS.Core;
using nanoCMS.Forum.Concrete;

namespace nanoCMS.Forum.Providers
{
    public class ForumUserInfoProvider
    {
        private readonly WorldContext worldContext;
        private ForumEntities _entities; //DO NOT ACCESS DIRECTLY
        private ForumEntities Entities
        {
            get { return _entities ?? (_entities = new ForumEntities(worldContext.EntityConnectionString)); }
        }

        public ForumUserInfoProvider(WorldContext worldContext)
        {
            this.worldContext = worldContext;
        }

        public ForumUserInfo Add(int userId)
        {
            ForumUserInfo info = new ForumUserInfo()
            {
                UserID = userId,
                PostCount = 0,
                SignatureContent = ""
            }; 
            Entities.ForumUserInfo.AddObject(info);
            Entities.SaveChanges();
            return info; 
        }

        public ForumUserInfo Get(int userId)
        {
            ForumUserInfo info = Entities.ForumUserInfo.Where(p => p.UserID == userId).SingleOrDefault(); 
            if(info != null)
            {
                return info; 
            }
            else
            {
                return Add(userId); 
            }
        }

        public void IncreasePostCount(int userId)
        {
            ForumUserInfo info = Entities.ForumUserInfo.Where(p => p.UserID == userId).SingleOrDefault();
            if (info == null)
            {
                info = Add(userId); 
            }
            if(info != null)
            {
                info.PostCount++;
                Entities.SaveChanges(); 
            }
        }

        public void DecreasePostCount(int userId)
        {
            ForumUserInfo info = Entities.ForumUserInfo.Where(p => p.UserID == userId).SingleOrDefault();
            if (info == null)
            {
                info = Add(userId);
            }
            if (info != null)
            {
                if (info.PostCount > 0)
                {
                    info.PostCount--;
                }
                Entities.SaveChanges();
            }
        }
    }
}